package com.heima.app.gateway.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-10-18 14:46
 */
//认证全局过滤器
@Component
//@Order(0)
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //1.判断是否是登录请求，是就放行  login auth -> login%20auth ->getPath login auth
        if(request.getURI().getPath().contains("/login/login_auth")){
            return chain.filter(exchange); //容易忘记return
        }

        //2.获取token，校验token是否存在
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isBlank(token)){
            //返回错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //3.校验token是否有效
        try{
            Claims claimsBody = AppJwtUtil.getClaimsBody(token); //获取payload载荷 包含过期时间
            int verifyToken = AppJwtUtil.verifyToken(claimsBody);//校验token是否过期 1和2有问题情况
            if(verifyToken == 1 || verifyToken == 2){
                //返回错误
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
//            if(verifyToken == 0){
//                //快要过期了
//                //response 添加响应头 SET-EXPIRE  1 前端再发一个请求刷新token
//            }
            //解析ID
            Long id = claimsBody.get("id", Long.class);
            //将id存放到请求头中进行传递
            ServerHttpRequest newRequest = request.mutate().
                    header("userId", id.toString()).build();
            exchange.mutate().request(newRequest).build();

        }catch (Exception e){
            //返回错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //4.放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
